package com.beici.waterghost.controller;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码生成器
 * @auther WaterGhost
 * @date 2022/3/10 12:09
 */
@RequestMapping("/code")
@RestController
@CrossOrigin
public class verifityCodeGennerController {

    @Autowired
    private Producer producer;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/verfcode")
    public String getVerfitiyCode(Long phone){
        // 生成验证码
        String text = producer.createText();
        // 写入redis
        addCode(String.valueOf(phone),text);
        // 生成验证码
        BufferedImage image = producer.createImage(text);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image,"jpg",byteArrayOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = byteArrayOutputStream.toByteArray();
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String encode = base64Encoder.encode(bytes);
        return encode;
    }

    private void addCode(String phone,String code){
        redisTemplate.opsForValue().set(phone+"verifitycode",code,3, TimeUnit.MINUTES);
    }
}
